#include <pthread.h>
#include <unistd.h>
#include <iostream>
#include <vector>
#include <string>
#include "thread.hpp"
pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;    // 条件变量
pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER; // 互斥锁
bool turn = false;

void *thread1(void *args)
{
    while (1)
    {
        pthread_mutex_lock(&gmutex);
        while (turn)
        {
            pthread_cond_wait(&gcond, &gmutex);
            sleep(1);
        }
        std::string name = static_cast<const char *>(args);
        std::cout << "我是线程" << name << std::endl;
        turn = true;
        pthread_cond_signal(&gcond);
        pthread_mutex_unlock(&gmutex);
    }
}
void *thread2(void *args)
{
    while (1)
    {
        pthread_mutex_lock(&gmutex);
        while (!turn)
        {
            pthread_cond_wait(&gcond, &gmutex);
            sleep(1);
        }
        std::string name = static_cast<const char *>(args);
        std::cout << "我是线程" << name << std::endl;
        turn = false;
        pthread_cond_signal(&gcond);
        pthread_mutex_unlock(&gmutex);
    }
}

int main()
{
    pthread_t t1, t2;
    const char *A = "A";
    const char *B = "B";

    pthread_create(&t1, nullptr, thread1, (void *)A);
    pthread_create(&t2, nullptr, thread2, (void *)B);

    // 初始阶段触发第一个线程
    pthread_mutex_lock(&gmutex);
    pthread_cond_signal(&gcond); // 启动线程1
    pthread_mutex_unlock(&gmutex);

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    return 0;
}